package com.ksy.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * Created by Ksy.
 */

public class PermissionUtils {
    public static class PermissionState {
        public String permission;
        public State state;

        public PermissionState() {

        }

        @Override
        public String toString() {
            return "PermissionState{" +
                    "permission='" + permission + '\'' +
                    ", state=" + state +
                    '}';
        }
    }

    public enum State {
        Pass,
        Deny,
        NoAsk
    }

    public static final int SettingCode = 996;

    //用于在设置界面返回后再次检验
    public static void toAppSetting(Activity activity,int requestCode, String appId) {
        try {
            activity.startActivityForResult(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.parse("package:" + appId)),
                    requestCode);
        } catch (Exception ignored) {
        }
    }

    public static void toAppSetting(Fragment fragment, int requestCode, String appId) {
        try {
            fragment.startActivityForResult(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.parse("package:" + appId)),
                    requestCode);
        } catch (Exception ignored) {
        }
    }

    public interface PermissionListener {
        void onPermission(boolean isAllPass, PermissionState... permissionStates);
    }

    public static void requestPermission(@NonNull Activity activity, final PermissionListener listener, @NonNull final String... permissions) {
        RxPermissions rxPermissions = new RxPermissions(activity);
        Observable<Permission> observable = rxPermissions.requestEach(permissions);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Permission>() {
            PermissionState[] states = new PermissionState[permissions.length];
            int index = 0;
            boolean isAllPass=true;

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Permission permission) {
                PermissionState state = new PermissionState();
                state.permission = permission.name;
                if (permission.granted) {
                    isAllPass&=true;
                    LogTool.e("用户已经同意该权限    " + permission.name);
                    state.state = State.Pass;
                } else if (permission.shouldShowRequestPermissionRationale) {
                    LogTool.e("用户拒绝了该权限  那么下次再次启动时，还会提示请求权限的对话框  " + permission.name);
                    isAllPass&=false;
                    state.state = State.Deny;
                } else {
                    LogTool.e("用户拒绝了该权限，并且选中 不再询问 " + permission.name);
                    isAllPass&=false;
                    state.state = State.NoAsk;
                }
                states[index] = state;
                index++;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                listener.onPermission(isAllPass,states);
            }
        });

    }
    public static boolean isPermissionPass(@NonNull Activity activity, @NonNull String... perms) {
        boolean isAllPass = true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            isAllPass = true;
        } else {
            for (int i = 0; i < perms.length; i++) {
                isAllPass &= (ContextCompat.checkSelfPermission(activity, perms[i]) == PackageManager.PERMISSION_GRANTED);
            }
        }
        return isAllPass;
    }
  public static boolean isPermissionPass(@NonNull Context activity, @NonNull String... perms) {
        boolean isAllPass = true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            isAllPass = true;
        } else {
            for (int i = 0; i < perms.length; i++) {
                isAllPass &= (ContextCompat.checkSelfPermission(activity, perms[i]) == PackageManager.PERMISSION_GRANTED);
            }
        }
        return isAllPass;
    }

    /**
     * 返回权限状态集合
     *
     * @param activity
     * @param perms
     * @return
     */
    private static PermissionState[] hasPermission(@NonNull Activity activity, @NonNull String... perms) {
        PermissionState[] states = new PermissionState[perms.length];
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            for (int i = 0; i < perms.length; i++) {
                String perm = perms[i];
                PermissionState state = new PermissionState();
                state.permission = perm;
                state.state = State.Pass;
                states[i] = state;
            }
            return states;
        }
        for (int i = 0; i < perms.length; i++) {
            String perm = perms[i];
            PermissionState state = new PermissionState();
            state.permission = perm;
            if (ContextCompat.checkSelfPermission(activity, perm) == PackageManager.PERMISSION_GRANTED) {
                state.state = State.Pass;
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, perm)) {
                    //请求过权限 但遭到拒绝,
                    state.state = State.Deny;
                } else {
                    //请求过权限 但遭到拒绝,并且选择了不再提醒
                    state.state = State.NoAsk;
                }
            }
            states[i] = state;
        }
        return states;
    }


}
